
//
//  WebVC.m
//  itboyeios_gd
//
//  Created by Apple on 15/10/31.
//  Copyright © 2015年 Boye. All rights reserved.
//

#import "WebVC.h"
#import "NSString+Helper.h"
#import "RubyVC.h"
#import "WebViewController.h"

#import "PostReplyModel.h"


@interface WebVC ()<UMSocialUIDelegate>
{
    UILabel *_loadLabel; // 网页加载提示文字
    UIActivityIndicatorView *_indicatorView; // 网页加载菊花转动
}
@end

@implementation WebVC

// 自定义初始化方法，获取所要显示的网页的网址，并显示该网页
- (instancetype)initWithUrlString:(NSString *)urlString {
    self = [super init];
    if (self) {
        // 创建网页webView
        CGRect frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT- 15);
        _webView = [[UIWebView alloc] initWithFrame:frame];
        _webView.delegate = self;
        _webView.scalesPageToFit = YES;
        [self.view addSubview:_webView];
        
        // 发送请求，获取该网页内容
        urlString = [[NSString stringWithFormat:@"%@/%@", WEB_BASE_URL, urlString] stringByEncodingURLFormat];
        //urlString = [@"http://sunsun.itboye.com/index.php/Webview/Index/gainScore?uid=21&psw=e56d09a4e36a3281d98176728bf24683" stringByEncodingURLFormat];
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        [_webView loadRequest:request];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    
    //导航栏默认黄色
    if (!self.color) {
        self.color = SS_NAVI_ORANGE_COLOR;
    }
        // 设置背景颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:self.color] forBarMetrics:UIBarMetricsDefault];
    self.title =  self.titleString;
//    self.title = @"抽奖";
    // 进来的时候要隐藏导航栏
    MainTabBarController *tabBarController = (MainTabBarController *)self.navigationController.tabBarController;
    [tabBarController hideTabBar];
   
    //  创建导航栏左边返回按钮，此方法由父类实现
    [self createLeftBarButtonItemWithImagename:nil];
}
// 右侧按钮的样式可以自定义，由imgname控制，如果是文字则调用下面的接口
- (void)createRightBarButtonItemWithImagename:(NSString *)imgname {
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [rightButton addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setImage:[UIImage imageNamed:imgname] forState:UIControlStateNormal];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
}


#pragma mark - UIVebView代理方法
// 开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView {
    // 创建提示文字
    _loadLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    _loadLabel.text = @"加载中...";
    _loadLabel.textAlignment = NSTextAlignmentCenter;
    _loadLabel.textColor = [UIColor lightGrayColor];
    _loadLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:_loadLabel];
    
    // 加载网页时，菊花转动
    _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    CGPoint point = CGPointMake(self.view.width/4, -20);
    _indicatorView.center = point;
    [_loadLabel addSubview:_indicatorView];
    _indicatorView.hidesWhenStopped = YES;
    [_indicatorView startAnimating];
    }

// 加载结束
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // 加载提示移除
    [_indicatorView stopAnimating];
    [_loadLabel removeFromSuperview];
    _loadLabel = nil;
}


#pragma mark - 返回上一界面
// 返回上一界面，覆写父类方法
- (void)leftAction:(UIButton *)button {
    if (_webView.canGoBack) {
        [_webView goBack];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (BOOL)webView: (UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    
    NSString *shareText = self.model.post_title;
    NSString *url = [NSString stringWithFormat:@"%@/Post/viewPost?id=%@", WEB_BASE_URL, self.model.fid];
   
    // 微信处理
    [UMSocialWechatHandler setWXAppId:APPKEY_WEIXIN appSecret:APPSECRET_WEIXIN url:url];
    [UMSocialQQHandler setQQWithAppId:APPID_QQ appKey:APPKEY_QQ url:url];
    // TODO: 分享链接的问题®
    // 微博分享的处理
    [UMSocialData defaultData].extConfig.sinaData.shareText = shareText;
    [UMSocialData defaultData].extConfig.sinaData.urlResource.url = url;
    [UMSocialData defaultData].extConfig.sinaData.urlResource.resourceType = UMSocialUrlResourceTypeImage;
    
    // 微信消息类型
    [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
    
    // 微信朋友圈分享
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = shareText;
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = url;
    
    // 微信好友分享
    [UMSocialData defaultData].extConfig.wechatSessionData.title = shareText;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = url;
    
    // qq分享
    [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
    [UMSocialData defaultData].extConfig.qqData.title = shareText;
    [UMSocialData defaultData].extConfig.qzoneData.title = shareText;
    [UMSocialData defaultData].extConfig.qqData.url = url;
    [UMSocialData defaultData].extConfig.qzoneData.url = url;

    UIImageView * imageView  = [[UIImageView alloc] init];
    
    
    
    UserModel *user = [CommonCache getUserInfo];

    NSString *requestString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSLog(@"请求网址  ＝ %@", requestString);

    if ([requestString hasPrefix:@"com.itboye.sunsunchina:"]) {
        
            NSArray *kv = [requestString componentsSeparatedByString:@"="];
            NSString * getString;
            if (kv.count == 2) {
                getString =[[kv objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            }
        
        if ([getString isEqualToString:@"SUNSUN_RED_ENVELOPE"]) {//查看购物券
            RubyVC  *vc = [[RubyVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if ([getString isEqualToString:@"MORE_SCORE"]) {//如何获取更多积分
            WebViewController  *vc = [[WebViewController alloc] initWithUrlString:[NSString stringWithFormat:@"http://sunsun.itboye.com/index.php/Webview/Index/gainScore?uid=%@&psw=%@", user.uid, user.password]];
            vc.titleString = @"如何获取更多积分";
            [self.navigationController pushViewController:vc animated:YES];
        }else if ([getString isEqualToString:@"SHOW_LOG"]) {//积分兑换记录
            WebViewController  *vc = [[WebViewController alloc] initWithUrlString:[NSString stringWithFormat:@"http://sunsun.itboye.com/index.php/Webview/Webview/ExchangeLog/index?uid=%@&psw=%@", user.uid, user.password]];
            vc.titleString = @"积分兑换记录";
            [self.navigationController pushViewController:vc animated:YES];
        }else if ([getString hasPrefix: @"SGOODS_DETAIL"]) {//商品详情
            NSMutableString * tempString = [NSMutableString stringWithString:getString];
            [tempString deleteCharactersInRange:NSMakeRange(0, getString.length - 1)];
            
            NSString * index = tempString;
            WebViewController  *vc = [[WebViewController alloc] initWithUrlString:[NSString stringWithFormat:@"http://sunsun.itboye.com/index.php/Webview/ScoreGoods/detail?uid=%@&psw=%@&pid=%@", user.uid, user.password, index]];
            vc.titleString = @"商品详情";
            [self.navigationController pushViewController:vc animated:YES];
        }else if ([getString isEqualToString:@"SUNSUN_SHARE_QQ"]){//QQ分享
            [imageView setImageURLStr:self.model.main_img placeholder:DEFAULT_IMAGE];
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQQ]
                                                               content:self.model.post_excerpt
                                                                 image:imageView.image//[UIImage getImageFromURL:self.model.main_img]
                                                              location:nil
                                                           urlResource:nil
                                                   presentedController:self
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                if (response.responseCode == UMSResponseCodeSuccess) {
                                                                    NSLog(@"分享成功！");
                                                                }
                                                            }];

            
            
        }else if ([getString isEqualToString:@"SUNSUN_SHARE_WECHAT"]){//微信分享
            
            [imageView setImageURLStr:self.model.main_img placeholder:DEFAULT_IMAGE];
                    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession]
                                                                       content:self.model.post_excerpt
                                                                         image:imageView.image
                                                                      location:nil
                                                                   urlResource:nil
                                                           presentedController:self
                                                                    completion:^(UMSocialResponseEntity *response) {
                        if (response.responseCode == UMSResponseCodeSuccess) {
                            NSLog(@"分享成功！");
                        }
                    }];



        }else if ([getString isEqualToString:@"SUNSUN_SHARE_CIRCLE"]){//朋友圈分享
            
            [imageView setImageURLStr:self.model.main_img placeholder:DEFAULT_IMAGE];
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatTimeline]
                                                               content:self.model.post_excerpt
                                                                 image:imageView.image
                                                              location:nil
                                                           urlResource:nil
                                                   presentedController:self
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                if (response.responseCode == UMSResponseCodeSuccess) {
                                                                    NSLog(@"分享成功！");
                                                                }
                                                            }];

            
           
        }
        return NO;
    }
    return YES;
}

// 新闻分享
- (void)rightAction:(UIButton *)button{
    
    NSString *shareText = self.model.post_title;
    NSString *url = [NSString stringWithFormat:@"%@/Post/viewPost?id=%@", WEB_BASE_URL, self.model.fid];
    // 微信处理
    [UMSocialWechatHandler setWXAppId:APPKEY_WEIXIN appSecret:APPSECRET_WEIXIN url:url];
    [UMSocialQQHandler setQQWithAppId:APPID_QQ appKey:APPKEY_QQ url:url];
    
    
    // TODO: 分享链接的问题®
    // 微博分享的处理
    [UMSocialData defaultData].extConfig.sinaData.shareText = shareText;
    [UMSocialData defaultData].extConfig.sinaData.urlResource.url = url;
    [UMSocialData defaultData].extConfig.sinaData.urlResource.resourceType = UMSocialUrlResourceTypeImage;
    
    // 微信消息类型
    [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
    
    // 微信朋友圈分享
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = shareText;
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = url;
    
    // 微信好友分享
    [UMSocialData defaultData].extConfig.wechatSessionData.title = shareText;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = url;
    
    // qq分享
    [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
    [UMSocialData defaultData].extConfig.qqData.title = shareText;
    [UMSocialData defaultData].extConfig.qzoneData.title = shareText;
    [UMSocialData defaultData].extConfig.qqData.url = url;
    [UMSocialData defaultData].extConfig.qzoneData.url = url;
    UIImageView * imageView  = [[UIImageView alloc] init];
    [imageView setImageURLStr:self.model.main_img placeholder:DEFAULT_IMAGE];
    // 实现分享
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:APPKEY_UMENG_SOCIAL
                                      shareText:self.model.post_excerpt
                                     shareImage:imageView.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToQQ,UMShareToWechatSession,UMShareToWechatTimeline,nil]
                                       delegate:self];
    
    
//     //使用自定义分享列表面板，则在对应的（微信，qq，微博等）分享按钮中实现下面的方法
//        [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession]
//                                                           content:self.model.post_excerpt
//                                                             image:self.model.main_img
//                                                          location:nil
//                                                       urlResource:nil
//                                               presentedController:self
//                                                        completion:^(UMSocialResponseEntity *response) {
//            if (response.responseCode == UMSResponseCodeSuccess) {
//                NSLog(@"分享成功！");
//            }
//        }];

    
}



@end
